# packingtools/ios_packer.py
import os
import subprocess
import platform
import shutil

# ------------------------------------------------------------------------------
# 路径转换
# ------------------------------------------------------------------------------
def _windows_path_to_wsl(path: str) -> str:
    """
    将 Windows 绝对路径转换为 WSL 路径。
    优先使用 wslpath，其次手动转换。
    """
    path = os.path.abspath(path)
    try:
        proc = subprocess.run(
            ["wsl", "wslpath", "-a", path],
            capture_output=True, text=True, check=True,
            encoding="utf-8", errors="ignore"
        )
        return proc.stdout.strip()
    except Exception:
        # 手动兜底：C:\xxx -> /mnt/c/xxx
        path = path.replace("\\", "/")
        if len(path) >= 2 and path[1] == ":":
            drive = path[0].lower()
            return f"/mnt/{drive}{path[2:]}"
        raise ValueError(f"无法转换路径: {path}")

# ------------------------------------------------------------------------------
# 上传主逻辑
# ------------------------------------------------------------------------------
def upload_project_to_wsl(source_dir: str, log_callback, message_callback):
    """
    将 Windows 项目完整复制到 WSL Ubuntu-22.04 的 ~/projects/<项目名> 目录。
    支持隐藏文件、软链、权限保持及实时进度。
    """
    if platform.system() != "Windows":
        message_callback("操作不支持", "此功能仅在 Windows 上可用。")
        return

    if not os.path.isdir(source_dir):
        log_callback("❌ 源目录不存在。")
        message_callback("上传失败", "源目录不存在。")
        return

    project_name = os.path.basename(source_dir.rstrip("\\/"))
    src_wsl = _windows_path_to_wsl(source_dir)
    dst_wsl = f"~/projects/{project_name}"

    log_callback(f"Windows 源: {source_dir}")
    log_callback(f"WSL 源: {src_wsl}")
    log_callback(f"WSL 目标: {dst_wsl}")

    try:
        # 1. 创建目标父目录
        subprocess.run(
            ["wsl", "-d", "Ubuntu-22.04", "--", "bash", "-c", f"mkdir -p {dst_wsl}"],
            check=True, capture_output=True
        )

        # 2. 使用 rsync 复制（包含隐藏文件、权限、进度）
        cmd = [
            "wsl", "-d", "Ubuntu-22.04", "--",
            "rsync", "-a", "--info=progress2", "--no-inc-recursive",
            f"{src_wsl}/", f"{dst_wsl}/"
        ]

        # 若 rsync 不存在，退回到 cp -a
        fallback_cmd = [
            "wsl", "-d", "Ubuntu-22.04", "--",
            "bash", "-c",
            f"cp -aT {src_wsl}/ {dst_wsl}/"
        ]

        # 先尝试 rsync
        log_callback("[*] 开始复制文件...")
        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding="utf-8",
            errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW
        )

        for line in iter(proc.stdout.readline, ""):
            if line.strip():
                log_callback(line.strip())

        proc.wait()

        if proc.returncode != 0:
            log_callback("[!] rsync 失败，尝试 cp -a...")
            proc = subprocess.run(
                fallback_cmd,
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
            )
            for line in proc.stdout.splitlines():
                if line.strip():
                    log_callback(line.strip())

        if proc.returncode == 0:
            log_callback("\n✅ 文件已完整上传至 WSL。")
            message_callback("上传成功", f"项目已上传到:\n{dst_wsl}")
        else:
            log_callback("\n❌ 复制失败，请检查日志。")
            message_callback("上传失败", "复制过程中发生错误。请查看日志。")

    except subprocess.CalledProcessError as e:
        err = e.stderr or e.stdout or str(e)
        log_callback(f"❌ 命令错误: {err}")
        message_callback("命令错误", err)
    except FileNotFoundError:
        log_callback("❌ 未找到 wsl.exe，请确认已安装 WSL。")
        message_callback("环境错误", "未找到 wsl.exe")
    except Exception as e:
        log_callback(f"❌ 未知异常: {e}")
        message_callback("未知错误", str(e))